/*
 * FrameBuffer.cpp
 *
 *  Created on: 16.06.2011
 *      Author: kirill
 */

#include "CFrameBuffer.h"

CFrameBuffer::CFrameBuffer()
{
	glGenFramebuffers( 1, &FrameBufferName );
}

CFrameBuffer::~CFrameBuffer()
{
	glDeleteFramebuffers( 1, &FrameBufferName );
}

void CFrameBuffer::BindFrameBuffer( const bool Bind )
{
	glBindFramebuffer( GL_DRAW_FRAMEBUFFER, (Bind ? FrameBufferName : 0) );
}

void CFrameBuffer::SetRenderTarget( const GLenum Target, const CColorRenderBuffer *RenderTarget )
{
	GLuint BufferName = RenderTarget->GetBufferName();
	glFramebufferRenderbuffer( GL_DRAW_FRAMEBUFFER, Target, GL_RENDERBUFFER, BufferName );
}

void CFrameBuffer::SetRenderTarget( const GLenum Target, const CTextureRenderBuffer *RenderTarget )
{
	GLuint BufferName = RenderTarget->GetBufferName();
	glFramebufferTexture2D( GL_DRAW_FRAMEBUFFER, Target, GL_TEXTURE_2D, BufferName, 0);
}

bool CFrameBuffer::CheckFrameBuffer( )
{
	return ( GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus( GL_DRAW_FRAMEBUFFER ) );
}

//--------------------------------

CColorRenderBuffer::CColorRenderBuffer()
{
	glGenRenderbuffers( 1, &RenderBufferName );
}

void CColorRenderBuffer::TuneRenderBuffer( const GLenum format, const GLsizei width, const GLsizei height )
{
	glBindRenderbuffer( GL_RENDERBUFFER, RenderBufferName );
	glRenderbufferStorage( GL_RENDERBUFFER, format, width, height );
	glBindRenderbuffer( GL_RENDERBUFFER, 0 );
}

//-----------------------------

CTextureRenderBuffer::CTextureRenderBuffer()
{
	glGenTextures   ( 1, &RenderBufferName );
}

void CTextureRenderBuffer::TuneRenderBuffer( const GLenum format, const GLsizei width, const GLsizei height )
{
	glBindTexture   ( GL_TEXTURE_2D, RenderBufferName );

	glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
	glTexParameteri (GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
	glTexImage2D    ( GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, format, GL_UNSIGNED_BYTE, NULL );

	glBindTexture   ( GL_TEXTURE_2D, 0 );
}

void CTextureRenderBuffer::UpdateBuffer()
{
	glBindTexture(GL_TEXTURE_2D, RenderBufferName);
	glGenerateMipmap(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, 0);
}
